package gui.partb;

import java.io.*;

/**
 * 对文件进行对象序列化和反序列工具类
 *
 * @author Shuyue Si
 * @version 1.0 use jdk 1.8
 */
public class FileUtils {
    /**
     * 序列化把对象存储到文件中
     *
     * @param obj 序列化对象
     * @param url 文件路径
     */
    public static void writeObjectToFile(Object obj, String url) {
        File file = new File(url);
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            ObjectOutputStream objOut = new ObjectOutputStream(out);
            objOut.writeObject(obj);
            objOut.flush();
            objOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 反序列化从文件中读取对象信息
     *
     * @param url 文件位置
     * @return 返回文件存储的对象
     */
    public static Object readObjectFromFile(String url) {
        Object temp = null;
        File file = new File(url);
        if (file.exists()) {
            FileInputStream in;
            try {
                in = new FileInputStream(file);
                ObjectInputStream objIn = new ObjectInputStream(in);
                temp = objIn.readObject();
                objIn.close();
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
            return temp;
        }
        return null;
    }
}
